<template>
  <div v-for="(item, index) in schema" :key="'task' + index" class="task-form">
    <el-form v-if="formDatas[index]" :model="formDatas[index]" label-position="top">
      <el-form-item v-for="(el, i) in item.properties" :key="'task-item' + i" :label="el.description" :prop="el.title">
        <el-input-number v-if="el.type === 'integer'" v-model="formDatas[index][el.title]" :step-strictly="true" :disabled="disabled" />
        <el-input-number v-else-if="el.type === 'number'" v-model="formDatas[index][el.title]" :disabled="disabled" />
        <el-checkbox v-else-if="el.type === 'boolean'" v-model="formDatas[index][el.title]" :disabled="disabled" />
        <div v-else-if="el.type === 'array'">
          <ArrayelEment :ref="(eldata) => setRef(eldata, index, i)" :data="formDatas[index][el.title]" :items="el.items" :disabled="disabled" />
        </div>
        <el-input v-if="el.type === 'string'" v-model="formDatas[index][el.title]" :disabled="disabled" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup name="JsonSchemaElement" lang="ts">
import ArrayelEment from './arrayelEment.vue';
const props = defineProps({
  schema: {
    type: Array,
    default: () => []
  },
  data: {
    type: Array,
    default: () => [{}]
  },
  disabled: {
    type: Boolean,
    default: false
  }
});
const formDatas = ref([{}]);
watch(
  () => props.data,
  () => {
    if (props.data) {
      formDatas.value = props.data;
    }
  }
);

const refDatas = ref([]);
const setRef = (el, index, i) => {
  if (el) {
    refDatas.value[`arrayElementRef-${index}-${i}`] = el;
  }
};
const getData = () => {
  props.schema.forEach((item, index) => {
    for (const key in item.properties) {
      const el = item.properties[key];
      if (el.type === 'array') {
        const data = refDatas.value[`arrayElementRef-${index}-${key}`].getData();
        formDatas.value[index][el.title] = data;
      }
    }
  });
  return formDatas.value;
};
onMounted(() => {
  if (props.data) {
    formDatas.value = props.data;
  }
});
defineExpose({
  getData
});
</script>

<style lang="scss" scoped>
.task-form {
}
</style>
